<?php
/**
 * Created By Leroi Liu
 * Email：675667823@qq.com
 * Date：2023/2/12
 * Description：
 **/

namespace MicroCyan\ThinkHelp\Kernel;

class Upload
{

    /**
     * @param $object
     * @param $content
     * @param $bucket
     * @return string
     * @throws \Exception
     */
    public function SmallByOss($object,$content,$bucket=''): string
    {
        try {
            $oc = \think\facade\Config::get('alibaba.oss','');
            //简单验证object
            if ( !empty($object[0]) && $object[0] === '/'){
                $object = substr($object,1);
            }
            //简单验证URL
            if ( !empty($oc['url'][-1]) && $oc['url'][-1] === '/'){
                $oc['url'] = substr($object,0,-1);
            }
            //如果没有设置bucket，则使用默认的
            if (!preg_match('/^[a-z0-9\-]{2,}$/',$bucket)){
                $bucket = $oc['bucket'];
            }

            $ossClient = new \OSS\OssClient($oc['accessKeyId'],$oc['accessSecret'],$oc['endpoint']);
            $uplaod  = $ossClient->putObject($bucket, $object, $content);
            if (!empty($uplaod['oss-request-url']) && strlen($uplaod['oss-request-url'])>0 ){
                return $oc['url'].'/'.$object;
            }
            throw new \Exception('图片上传失败');
        }catch (\OSS\Core\OssException $e) {
            throw new \Exception($e->getMessage());
        }catch (\Exception $e){
            throw new \Exception($e->getMessage());
        }
    }


}
